package jm.easyconfig.standalone;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
//import com.rabbitmq.client.DeliverCallback;

@RestController
public class AmqpController {

	@Autowired
	Environment env;

	ConnectionFactory factory;
	Connection connection;
	Channel channel;

	final String EXCHANGE_NAME = "easyconfig_fanout";

	@PreDestroy
	public void destroy()
	{
		
	}
	
//	@PostConstruct
//	public void init() throws Throwable {
//		factory = new ConnectionFactory();
//		String addresses = env.getProperty("spring.rabbitmq.addresses", "");
//		factory.setHost(addresses);
//		factory.setUsername(env.getProperty("spring.rabbitmq.username", ""));
//		factory.setPassword(env.getProperty("spring.rabbitmq.password", ""));
//
//		connection = factory.newConnection();
//		channel = connection.createChannel();
//
//		channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);
//
//		final String queue = channel.queueDeclare().getQueue();
//		channel.queueBind(queue, EXCHANGE_NAME, "");
//
//		DeliverCallback deliverCallback = (consumerTa, delivery) -> {
//
//			String message = new String(delivery.getBody(), StandardCharsets.UTF_8);
//			System.out.println(" [x] Received '" + message + "'");
//
//		};
//
//		channel.basicConsume(queue, true, deliverCallback, consumerTag -> {
//		});
//		
//	}

	@PostMapping("/publish")
	public Object publish(@RequestBody String message) throws Throwable {
		channel.basicPublish(EXCHANGE_NAME, "", null, message.getBytes(StandardCharsets.UTF_8));

		System.out.println(" [x] Sent '" + message + "'");

		return message;
	}

}
